package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        //1.获取当前登录用户  能进来 肯定就不是null
        //Employee employee = (Employee) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        //获取当前 登录用户
        Employee employee = UserContext.getCurrentUser();

        //2.判断是否 超级管理员
        if (employee.isAdmin()) {
            //是 放行
            return true;
        }

        //不是  --3
        //3.获取请求目标方法(Spring 拦截器mvc 拦截 的请求方法,参数写的是Object类型 , 不能直接调用子类里面的方法)
        HandlerMethod method = (HandlerMethod) handler;
        //4.判断方法上是否有贴自定义注解
        RequiresPermissions annotation = method.getMethodAnnotation(RequiresPermissions.class);
        if (annotation == null) {
            return true;
            //没有  放行
        }
        // 有  --> 5.
        /////////////////////////////////////////
        //5.从注解上获取 权限表达式
        String expression = annotation.value()[0];
        System.out.println(expression);

        //6.获取当前登录当前用户拥有的权限列表
        //------
        //List<String> expressions = permissionMapper.selectExpressionByEmpId(employee.getId());

        //List<String> list = (List<String>) request.getSession().getAttribute(UserContext.EXPRESSION_IN_SESSION);
        List<String> list = UserContext.getExpression();


        //7.判断目标方法
        if (list.contains(expression)){
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
